const validator = require('validator');
const eventproxy     = require('eventproxy');
const tools          = require('../common/tools');
const mail           = require('../common/mail');
const utility        = require('utility');
const Response = require('../common/Response');
const User = require('../proxy').User;
const authMiddleWare = require('../middlewares/auth');
const config = require('../config');

//sign up
exports.signup = function(req, res, next) {
    let loginName = validator.trim(req.body.loginName).toLowerCase();
    let email = validator.trim(req.body.email).toLowerCase();
    let pass = validator.trim(req.body.pass);
    let rePass = validator.trim(req.body.re_pass);

    let ep = new eventproxy();
    // ep.fail(next);
    ep.on('prop_err', function(msg) {
        let response = new Response(0, '', msg);
        res.send(response);
    });

    //验证信息的正确性
    if([loginName, pass, rePass, email].some(item => item === '')) {
        ep.emit('prop_err', '信息不完整。');
        return;
    }
    if(loginName.length < 3) {
        ep.emit('prop_err', '用户名至少需要5个字符串。');
        return;
    }
    if(!tools.validateId(loginName)) {
        return ep.emit('prop_err', '用户名不合法。');
    }
    if(!validator.isEmail(email)) {
        return ep.emit('prop_err', '邮箱不合法。');
    }
    if(pass !== rePass) {
        return ep.emit('prop_err', '两次密码输入不一致。');
    }
    //end 验证信息的正确性

    User.getUsersByQuery({'$or': [
        {'loginName': loginName},
        {'email': email}
    ]}, {}, function(err, users) {
        if(err) {
            return next(err);
        }
        if(users.length > 0) {
            ep.emit('prop_err', '用户名或邮箱已被使用。');
            return;
        }

        tools.bhash(pass, ep.done(function (passhash) {
            // create gravatar
            // var avatarUrl = User.makeGravatar(email);
            let avatarUrl = '';
            User.newAndSave(loginName, loginName, passhash, email, avatarUrl, false, function (err) {
                if (err) {
                    return next(err);
                }
                // 发送激活邮件
                mail.sendActiveMail(email, utility.md5(email + passhash + config.session_secret), loginName);

                let response = new Response(1, '', '欢迎加入 ,我们已给您的注册邮箱发送了一封邮件，请点击里面的链接来激活您的帐号。');
                res.send(response);
            });

        }));
    })
};

/**
 * Handle user login.
 *
 * @param {HttpRequest} req
 * @param {HttpResponse} res
 * @param {Function} next
 */

exports.login = function(req, res, next) {
    let loginName = validator.trim(req.body.loginName).toLowerCase();
    let pass = validator.trim(req.body.pass);
    let ep = new eventproxy();

    // ep.fail(next);

    if(!loginName || !pass) {
        let response = new Response(0, '', '信息不完整');
        return res.json(response);
    }

    let getUser;
    if(loginName.indexOf('@') !== -1) {
        getUser = User.getUserByMail;
    } else {
        getUser = User.getUserByLoginName;
    }

    ep.on('login_error', function (login_error) {
        let response = new Response(0, '', '用户名或密码错误');
        res.json(response);
    });

    getUser(loginName, function (err, user) {
        if(err) {
            return next(err);
        }
        if(!user) {
            return ep.emit('login_error');
        }

        let passhash = user.pass;
        tools.bcompare(pass, passhash, ep.done(function (bool) {
            if(!bool) {
                return ep.emit('login_error');
            }

            if(!user.active) {
                //重新发送激活邮件
                mail.sendActiveMail(user.email, utility.md5(user.email + passhash + config.session_secret), user.loginname);
                let response = new Response(0, '', '此帐号还没有被激活，激活链接已发送到 ' + user.email + ' 邮箱，请查收。');
                return res.send(response);
            }
            // store session cookie
            authMiddleWare.gen_session(user, req, res);

            req.session.user = user;
            //check at some page just jump to home page
            // let refer = req.session._loginReferer;
            let result = {
                code: 1,
                data: user
            };
            let response = new Response(1, user, '登录成功');
            res.send(response);
        }));
    })
};

//sign out
exports.signout = function (req, res, next) {
    // req.session.destroy();
    req.session.user = null;
    res.clearCookie(config.auth_cookie_name);
    let response = new Response(1, '', '已退出');
    res.send(response);
};

exports.activeAccount = function (req, res, next) {
    let key  = validator.trim(req.query.key);
    let name = validator.trim(req.query.name);

    User.getUserByLoginName(name, function (err, user) {
        if (err) {
            return next(err);
        }
        if (!user) {
            return next(new Error('[ACTIVE_ACCOUNT] no such user: ' + name));
        }
        let passhash = user.pass;
        if (!user || utility.md5(user.email + passhash + config.session_secret) !== key) {
            let resposne = new Response(0, '/login', '信息有误，帐号无法被激活。');
            return res.json(resposne);
        }
        if (user.active) {
            let resposne = new Response(0, '/login', '帐号已经是激活状态。');
            return res.json(resposne);
        }
        user.active = true;
        user.save(function (err) {
            if (err) {
                return next(err);
            }
            let resposne = new Response(1, '/login', '帐号已被激活，请登录。');
            return res.json(resposne);
        });
    });
};